package com.hefu.virtuallife.base;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import butterknife.ButterKnife;
import butterknife.Unbinder;


public abstract class BaseFragment extends Fragment {

    private BaseActivity activity;
    private View rootView;

    private Unbinder butterKinfeBinder;

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);
        if (activity instanceof BaseActivity) {
            this.activity = (BaseActivity) activity;
            return;
        }
        throw new IllegalStateException("Makesure fragment's activity is BaseActivity!!!");
    }

    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView != null) {
            return rootView;
        }
        rootView= inflater.inflate(this.setLayoutId(), container, false);
        return rootView;
    }


    @Override
    public final void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        butterKinfeBinder = ButterKnife.bind(this, view);
        init(savedInstanceState, view);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        butterKinfeBinder.unbind();
    }

    protected abstract int setLayoutId();

    protected abstract void init(Bundle savedInstanceState, View view);


    protected BaseActivity getBaseActivity() {
        if (activity == null) {
            return (BaseActivity) getActivity();
        }
        return activity;
    }

}
